﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using ReportingServices.DeploymentCenter.Core;
using ReportingServices.DeploymentCenter.Core.Logging;
using ReportingServices.DeploymentCenter.Core.ReportingServicesServiceReference;

namespace ReportingServices.DeploymentCenter.UI
{
    public partial class SettingsForm : BaseForm
    {
        #region Constructors

        public SettingsForm()
        {
            InitializeComponent();

            LoadSettings();
        }

        #endregion

        #region Methods

        private void AddTreeNode(CatalogItem item)
        {
            string key = String.Empty;
            string[] pathParts = item.Path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            if (pathParts.Length == 1)
            {
                key = String.Format("/{0}", pathParts[0]);
            }
            else
            {
                for (int i = 0; i < pathParts.Length - 1; i++)
                {
                    key += "/" + pathParts[i];
                }
            }

            TreeNode newChildNode = new TreeNode(item.Name);
            newChildNode.Name = item.Path;

            TreeNode workingTreeNode = null;
            TreeNode[] foundNodes = DeploymentPathTreeView.Nodes.Find(key, true);

            if (foundNodes != null && foundNodes.Count() > 0)
                workingTreeNode = foundNodes[0];

            if (workingTreeNode == null)
            {
                if (DeploymentPathTreeView.Nodes["/"] != null)
                    DeploymentPathTreeView.Nodes["/"].Nodes.Add(newChildNode);
                else
                    DeploymentPathTreeView.Nodes.Add(newChildNode);
            }
            else
                workingTreeNode.Nodes.Add(newChildNode);
        }

        private void GetReportServerFolders()
        {
            Logger.LogInformation("Begin report server folder query.");

            CatalogItem[] catalogItems = null;

            using (DeploymentManager deploymentManager = new DeploymentManager(ReportingServicesServiceConfiguration))
            {
                catalogItems = deploymentManager.GetReportServerFolders("/", true);
            }

            if (catalogItems == null)
                return;

            DeploymentPathTreeView.Nodes.Clear();

            TreeNode rootNode = new TreeNode("Root Folder");
            rootNode.Name = "/";
            DeploymentPathTreeView.Nodes.Insert(0, rootNode);

            foreach (CatalogItem item in catalogItems)
            {
                if (item.TypeName.ToLowerInvariant() == "folder")
                {
                    AddTreeNode(item);
                }
            }

            Logger.LogInformation("End report server folder query.");
        }

        private void LoadSettings()
        {
            Logger.LogInformation("Load Settings");

            ReportServerUrlTextBox.Text = Properties.Settings.Default.ReportServer;
            UsernameTextBox.Text = String.Format("{0}\\{1}", Properties.Settings.Default.Domain, Properties.Settings.Default.UserName);
            PasswordTextBox.Text = Properties.Settings.Default.Password;

            if (!String.IsNullOrWhiteSpace(Properties.Settings.Default.ReportServer) &&
                !String.IsNullOrWhiteSpace(Properties.Settings.Default.Domain) &&
                !String.IsNullOrWhiteSpace(Properties.Settings.Default.UserName) &&
                !String.IsNullOrWhiteSpace(Properties.Settings.Default.Password))
            {
                GetReportServerFolders();

                if (!String.IsNullOrWhiteSpace(Properties.Settings.Default.DeploymentFolder))
                {
                    TreeNode[] nodes = DeploymentPathTreeView.Nodes.Find(Properties.Settings.Default.DeploymentFolder, true);

                    if (nodes != null && nodes.Length > 0)
                    {
                        DeploymentPathTreeView.SelectedNode = nodes[0];
                        DeploymentPathTreeView.Select();
                    }
                }
            }

            Logger.LogInformation("Loading Settings Complete.");
        }

        private void SaveSettings()
        {
            Properties.Settings.Default.ReportServer = ReportServerUrlTextBox.Text;

            string[] domainUsername = UsernameTextBox.Text.Trim().Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);

            if (domainUsername == null || domainUsername.Length < 2)
                throw new ArgumentException("Please enter a valid domain\\username.");

            Properties.Settings.Default.Domain = domainUsername[0];
            Properties.Settings.Default.UserName = domainUsername[1];
            Properties.Settings.Default.Password = PasswordTextBox.Text;

            if (DeploymentPathTreeView.SelectedNode != null)
                Properties.Settings.Default.DeploymentFolder = DeploymentPathTreeView.SelectedNode.Name;

            Properties.Settings.Default.Save();            
        }

        #endregion

        #region Event Handlers

        private void CloseButton_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void RefreshButton_Click(object sender, EventArgs e)
        {
            try
            {
                SaveSettings();
                LoadSettings();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void SaveSettingsButton_Click(object sender, EventArgs e)
        {
            try
            {
                SaveSettings();
                Close();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        #endregion
    }
}